<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use \think\helper\Str;
use think\Session;
function login_manager(){
  return session("manager");
}

function login_manager_id(){
  $manager = login_manager();
  if(empty($manager)){
    return 0;
  }else{
    return $manager["id"];
  }
}

function login_member(){
  return session("member");
}

function login_member_id(){
  $member = login_member();
  if(empty($member)){
    return 0;
  }else{
    return $member["id"];
  }
}

function login_user(){
  $user = login_member();
  if(empty($user)){
    return login_manager();
  }else{
    return $user;
  }
}

function login_user_id(){
  $user = login_user();
  if(empty($user)){
    return 0;
  }else{
    return $user["id"];
  }
}

/**
 * 用户头像URL
 * @Author zhanghong
 * @Date   2017-01-16
 * @param  [type]     $user_avatar [description]
 * @return [type]           [description]
 */
function show_user_avatar_url($user_avatar){
  if(is_array($user_avatar) || is_object($user_avatar)){
    if(isset($user_avatar["avatar"])){
      $img_path = $user_avatar["avatar"];
    }else{
      $img_path = null;
    }
  }else{
    $img_path = $user_avatar;
  }

  if(empty($img_path)){
    $img_path = "/static/index/images/1.png";
  }

  return $img_path;
}


/**
 * 读取网站设置
 * @Author zhanghong
 * @Date   2017-01-03
 */
function settings(){
  $list = \think\Db::name('options')->select();
  foreach ($list as $key => $opt) {
    $val = json_decode($opt["value"], true);
    think\Config::set($opt["name"], $val);
  }
}

// 应用公共文件
function get_field_text($field_name, $val){
  switch ($field_name) {
  case "status":
    $list = list_field_status();
    break;
  case "menu_status":
    $list = list_field_menu_status();
    break;
  case "article_type":
    $list = list_field_article_type();
    break;
  default:
    $list = [];
    break;
  }

  if($list[$val]){
    return $list[$val];
  }else{
    return $val;
  }
}

/**
* 格式化显示时间
* @param int_time string 时间值
* @param type string 输入格式
* @return string
*/
function format_show_time($int_time, $type = ""){
  if(empty($int_time)){
    return "";
  }else if(is_numeric($int_time)){
    switch ($type) {
    case 'zh_time':
      $format_str = "m月d日 H:i:s";
      break;
    case 'no_second':
      $format_str = "Y-m-d H:i";
      break;
    case 'date_node':
      $format_str = "Y.m.d";
      break;
    case 'small_date_node':
      $format_str = "y.m.d";
      break;
    case 'no_year_node':
      $format_str = "m.d H:i:s";
      break;
    case 'short_node':
      $format_str = "m.d";
      break;
    case 'only_date':
      $format_str = "Y-m-d";
      break;
    case 'month_day':
      $format_str = "m-d";
      break;
    case 'date_dir':
      $format_str = "Y/m/d";
      break;
    case 'ymd_dir':
      $format_str = "Ymd";
      break;
    case 'weekday':
      $format_str = "D";
      break;
    default:
      $format_str = "Y-m-d H:i:s";
      break;
    }
    return date($format_str, $int_time);
  }else{
    return $int_time;
  }
}

function list_field_status(){
  return ["0" => "草稿", "1" => "发布"];
}

function list_field_menu_status(){
  return ["1" => "显示", "0" => "隐藏"];
}

function list_field_user_gender(){
  return ["" => "未知", "male" => "男", "female" => "女"];
}

function list_field_article_type(){
  return ["" => "未知", "News" => "新闻", "Note" => "笔记"];
}

/**
 * 根据视频的URL地址求出视频来源类型和ID
 * @Author zhanghong
 * @Date   2017-03-05
 * @param  string     $url 视频URL
 * @return array
 */
function match_video_info($url){
  $res = [];
  $type = "";
  $sid = "";
  if(stripos($url, "youku")){
    $type = "youku";
    preg_match('/id_(\S+)\.html/', $url, $matches);
    if(!empty($matches)){
      $sid = $matches[1];
    }
  }else if(stripos($url, "v.qq")){
    $type = "qq";
    preg_match('/\/(\w+)\.html/', $url, $matches);
    if(!empty($matches)){
      $sid = $matches[1];
    }
    if(Str::startsWith($sid, "c")){
      $sid = Str::substr($sid, 1);
    }
  }
  $res = ["type" => $type, "sid" => $sid];
  return $res;
}

/**
 * 上传单张图片--系统自带的旧方法
 * @Author   zhanghong
 * @DateTime 2016-05-04
 * @param    string     $backcall 回调字段名
 * @param    integer    $width    图片高度
 * @param    integer    $height   图片宽度
 * @param    string     $id    当前图片对象ID
 * @param    string     $backcall_name    回调字段ID
 */
function upload_image_id($backcall="image", $width=100, $height=100, $id="", $backcall_name=""){
    if(empty($backcall_name)){
      $backcall_name = $backcall;
    }
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width='.$width.' height="'.$height.'"  src="'.url('index/upload/add').'?width='.$width.'&height='.$height.'&backcall='.$backcall.'&id='.$id.'&backcall_name='.$backcall_name.'"></iframe>
         <input type="hidden" name="'.$backcall_name.'" id="'.$backcall.'">';
}

function truncate($str, $length = 10, $truncate_string = "..."){
  $len = Str::length($str);
  if($len > $length){
    $sub_str = Str::substr($str, 0, $length);
    $val = $sub_str.$truncate_string;
  }else{
    $val = $str;
  }
  return $val;
}

/**
 * 检查是否是以手机浏览器进入(IN_MOBILE)
 */
function is_mobile_terminal() {
  $mobile = [];
  $mobile_browser_list = 'Mobile|iPhone|Android|WAP|NetFront|JAVA|OperasMini|UCWEB|WindowssCE|Symbian|Series|webOS|SonyEricsson|Sony|BlackBerry|Cellphone|dopod|Nokia|samsung|PalmSource|Xphone|Xda|Smartphone|PIEPlus|MEIZU|MIDP|CLDC';

  $user_agent = think\Request::instance()->header('user-agent');

  // note 获取手机浏览器
  if (preg_match ( "/$mobile_browser_list/i", $user_agent, $mobile )) {
    return true;
  } else {
    if (preg_match ( '/(mozilla|chrome|safari|opera|m3gate|winwap|openwave)/i', $user_agent)) {
      return false;
    } else {
      $param_mobile = think\Request::instance()->param("mobile");
      if ($param_mobile == 'yes') {
        return true;
      } else {
        return false;
      }
    }
  }
}

// 读取并清空session
function read_and_clear_session($name){
  $val = null;
  $val = Session::get($name);
  Session::delete($name);
  return $val;
}

/**
* 读取或存储weixin app info
* @param string|array $name session名称 如果为数组则表示进行session设置
* @param mixed $value session值
* @return mixed
*/
function session_weixin_app($appid='', $value=''){
  if(is_numeric($appid)){
    $AppModel = new \app\weixin\model\WeixinApp();
    $app = $AppModel->where("id", $appid)->find();
    if(empty($app)){
      $appid = "";
    }else{
      $appid = $app["appid"];
    }
  }
  $name = "app_{$appid}";
  if($value !== ''){
    Session::set($name, $value);
  }
  return Session::get($name);
}

// 读取或存储当前weixin app
function session_current_weixin_app($value=''){
  $name = "current_weixin_app";
  if(is_array($value) || is_object($value)){
    if(isset($value["appid"])){
      $appid = $value["appid"];
      // 把当前appid 设置成value里的appid(切换当前app id)
      Session::set($name, $appid);
    }else{
      // appid 错误
      $appid = null;
    }
  }else{
    $appid = Session::get($name);
  }
  if(is_null($appid)){
    return false;
  }
  return session_weixin_app($appid, $value);
}

/**
 * 切换Weixin App
 * @Author zhanghong
 * @Date   2017-05-08
 * @param  [type]     $appid [description]
 * @return [type]            [description]
 */
function change_current_weixin_app($appid){
  if(is_numeric($appid)){
    $field_name = "id";
  }else{
    $field_name = "appid";
  }
  $AppModel = new \app\weixin\model\WeixinApp();
  $weixin_app = $AppModel->where($field_name, $appid)->find();
  return session_current_weixin_app($weixin_app);
}

/**
* 读取或存储weixin user info
* @param string|array $name session名称 如果为数组则表示进行session设置
* @param mixed $value session值
* @return mixed
*/
function session_weixin_user($openid='', $value=''){
  if(is_numeric($openid)){
    $UserModel = new \app\weixin\model\WeixinUser();
    $user = $UserModel->where("id", $openid)->find();
    if(empty($user)){
      $openid = "";
    }else{
      $openid = $user["openid"];
    }
  }
  $name = "op_{$openid}";
  if($value !== ''){
    Session::set($name, $value);
  }
  return Session::get($name);
}

// 读取或存储当前weixin user
function session_current_weixin_user($value=''){
  $name = "session_current_openid";
  if(is_array($value) || is_object($value)){
    if(isset($value["openid"])){
      $openid = $value["openid"];
      // 把当前openid 设置成value里的openid(切换授权用户)
      Session::set($name, $openid);
    }else{
      $openid = null;
    }
  }else{
    $openid = Session::get($name);
  }
  if(is_null($openid)){
    return false;
  }
  return session_weixin_user($openid, $value);
}

function change_current_weixin_user($openid){
  $UserModel = new \app\weixin\model\WeixinUser();
  if(is_numeric($openid)){
    $field_name = "id";
  }else{
    $field_name = "openid";
  }
  $user = $UserModel->where($field_name, $openid)->find();
  return session_current_weixin_user($user);
}

/**
 * 获取缩略图
 * @param unknown_type $filename 原图路劲、url
 * @param unknown_type $width 宽度
 * @param unknown_type $height 高
 * @param unknown_type $cut 是否切割 默认不切割
 * @return string
 */
function get_thumb_image($filename, $width = 100, $height = 'auto',$cut=false, $replace = false){
  $upload_path = "";
  $info = pathinfo($filename);
  $oldFile = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . '.' . $info['extension'];
  $thumbFile = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . '_' . $width . '_' . $height . '.' . $info['extension'];

  $oldFile = str_replace('\\', '/', $oldFile);
  $thumbFile = str_replace('\\', '/', $thumbFile);

  $filename = ltrim($filename, '/');
  $oldFile = ltrim($oldFile, '/');
  $thumbFile = ltrim($thumbFile, '/');
  //原图不存在直接返回
  if (!file_exists($upload_path . $oldFile)) {
    @unlink($upload_path . $thumbFile);
    $info['src'] = $oldFile;
    $info['width'] = intval($width);
    $info['height'] = intval($height);
    return $info;
  //缩图已存在并且 replace替换为false
  } elseif (file_exists($upload_path . $thumbFile) && !$replace) {
    $imageinfo = getimagesize($upload_path . $thumbFile);
    //dump($imageinfo);exit;
    $info['src'] = $thumbFile;
    $info['width'] = intval($imageinfo[0]);
    $info['height'] = intval($imageinfo[1]);
    return $info;
  //执行缩图操作
  } else {
    $oldimageinfo = getimagesize($upload_path . $oldFile);
    $old_image_width = intval($oldimageinfo[0]);
    $old_image_height = intval($oldimageinfo[1]);
    if ($old_image_width <= $width && $old_image_height <= $height) {
      @unlink($upload_path . $thumbFile);
      @copy($upload_path . $oldFile, $upload_path . $thumbFile);
      $info['src'] = $thumbFile;
      $info['width'] = $old_image_width;
      $info['height'] = $old_image_height;
      return $info;
    } else {
      //生成缩略图 - 更好的方法
      if ($height == "auto") $height = 0;
      if ($width == "auto") $width = 0;
      think\Loader::import("PhpThumb.PhpThumbFactory", EXTEND_PATH, '.class.php');
      try{
        $thumb = \PhpThumbFactory::create($upload_path . $filename);
        if ($cut) {
          $thumb->adaptiveResize($width, $height);
        } else {
          $thumb->resize($width, $height);
        }
        $res = $thumb->save($upload_path . $thumbFile);
      }catch(\Exception $e){
        $res = NULL;
      }

      //缩图失败
      if (!$res) {
        $thumbFile = $oldFile;
      }
      $info['width'] = $width;
      $info['height'] = $height;
      $info['src'] = $thumbFile;
      return $info;
    }

  }
}


function get_thumb_src($picture_path, $width = 100, $height = 'auto', $cut = false, $replace = false){
  if(empty($picture_path)){
    return "";
  }
  $attach = get_thumb_image($picture_path, $width, $height, $cut, $replace);

  return "/".$attach['src'];
}

function comment_belongs_url($cmt_item){
  $link_url = "javascript:void(0);";
  if($cmt_item["belongs_type"] == "Article"){
    switch ($cmt_item['article_type']) {
    case 'Note':
      $link_url = url('index/note/read', array('id' => $cmt_item['belongs_id']));
      break;
    case 'News':
      $link_url = url('index/news/read', array('id' => $cmt_item['belongs_id']));
      break;
    }
  }
  return $link_url;
}